class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        vector<vector<int>> ret;
        sort(nums.begin(), nums.end());
        int n = nums.size();
        for (int i = 0; i < n;)
        {
            for (int j = i + 1; j < n;)
            {
                int left = j + 1;
                int right = n - 1;
                while (left < right)
                {
                    if ((long long int)nums[j] + nums[left] + nums[right] > target - nums[i])
                    {
                        right--;
                        while (left < right && nums[right + 1] == nums[right])right--;
                    }
                    else if ((long long int)nums[j] + nums[left] + nums[right] < target - nums[i])
                    {
                        left++;
                        while (left < right && nums[left - 1] == nums[left])left++;
                    }
                    else {
                        ret.push_back({ nums[i],nums[j],nums[left],nums[right] });
                        left++; right--;
                        while (left < right && nums[right + 1] == nums[right])right--;
                        while (left < right && nums[left - 1] == nums[left])left++;
                    }
                }
                j++;
                while (j < n && nums[j] == nums[j - 1])j++;
            }
            i++;
            while (i < n && nums[i] == nums[i - 1])i++;
        }

        return ret;
    }
};